Day27已經做到可以使用python來發送訊息至Chatbase
接著就來整合到Line Chatbot!!!
我是使用Day27所製作的專案並加入之前已經做好的Line Chatbot
所以整合的部分是從步驟三開始!
步驟一步驟二是重複說明一下Line Chatbot&Chatbase的部分
1.安裝&引入套件
分為Chatbot的部分跟Chatbase的部分
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import *
import requests
from bs4 import BeautifulSoup
from urllib.request import urlretrieve
import random
from chatbase import Message
2.Chatbot與Webhook設定
app = Flask(__name__)
line_bot_api = LineBotApi('YOUR_LineBot_Channel access token')
handler = WebhookHandler('YOUR_LineBot_Channel secret')
@app.route("/", methods=['GET'])
def hello():
return "Hello World!"
@app.route("/", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
print("Request body: " + body, "Signature: " + signature)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
爬蟲(最新電影)
def movie():
target_url = 'https://movies.yahoo.com.tw/'
print('Start parsing movie ...')
rs = requests.session()
res = rs.get(target_url, verify=False)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
content = ""
for index, data in enumerate(soup.select('div.movielist_info h1 a')):
if index == 20:
return content
print("data:")
print(index)
print(data)
title = data.text
link = data['href']
content += '{}\n{}\n'.format(title, link)
return content
3.整合!!!
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
msg = event.message.text
#print(type(msg))
msg = msg.encode('utf-8')
if event.message.text == "最新電影":
#加上傳送至Chatbase的程式
chatbase_msg = Message(api_key="",
type="user",
platform="Line",
version="1.0",
user_id="",
message=event.message.text,
intent="movie"
)
resp =chatbase_msg.send()
print(resp)
a=movie()
line_bot_api.reply_message(event.reply_token,TextSendMessage(text=a))
if event.message.text == "你好":
#加上傳送至Chatbase的程式
chatbase_msg = Message(api_key="",
type="user",
platform="Line",
version="1.0",
user_id="",
message=event.message.text,
intent="Hello"
)
resp =chatbase_msg.send()
print(resp)
line_bot_api.reply_message(event.reply_token,TextSendMessage(text=event.message.text))
4.來看看結果!!!
傳送訊息仍然有回覆結果
同時在Chatbase也會收到訊息
User messages數量增加
因為沒有設定Not handled,所以訊息都會歸在Handled
(不過不知道為什麼最新電影是亂字碼)